package com.aphrodite.extns.svg;

import java.io.IOException;
import java.io.InputStream;

import javax.microedition.lcdui.Image;
import javax.microedition.m2g.SVGImage;
import javax.microedition.m2g.ScalableGraphics;

public class SVGUtil {

	public static SVGImage getSVGImage(String path) {

		try {
			return getSVGImage(new Object().getClass().getResourceAsStream(path));
		} catch (IOException e) {
			System.out.println("[SVGUtil] " + e.toString());
			return null;
		}

	}

	public static SVGImage getSVGImage(InputStream is) throws IOException {
		try {
			return (SVGImage) SVGImage.createImage(is, null);
		} catch (IOException e) {
			System.out.println("[SVGUtil] " + e.toString());
			return null;
		}
	}

	/**
	 * Convert a SVGImage to a simple Image object.
	 * <p>
	 * The SVG image's view point settings need to be set, else the image
	 * location would reported wrong.
	 * </p>
	 * 
	 * @param svgimage
	 * @return
	 */
	public static Image toGenericImage(SVGImage svgimage) {
		int w = svgimage.getViewportWidth();
		int h = svgimage.getViewportHeight();

		Image tmp = Image.createImage(w, h);
		ScalableGraphics sg = ScalableGraphics.createInstance();
		sg.bindTarget(tmp.getGraphics());
		sg.render(0, 0, svgimage);
		sg.releaseTarget();
		return tmp;

	}
}
